package edu.upol.paradise.hypervisor;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.kevoree.library.nanohttp.NanoHTTPD;

public class HypervisorInfoService extends NanoHTTPD {
	static final Logger log = Logger.getLogger(HypervisorInfoService.class);
	
	private static final String MAIN = "main";
	
	public static interface PageFillingEvent {
		public String fillPage(String page, String data);
	}
	
	public static InputStream fromResourcesAsStream(String name){
		return HypervisorInfoService.class.getResourceAsStream("/"+name);
	}
	
	public static String fromResources(String name){
		try {
			return IOUtils.toString(fromResourcesAsStream(name));
		} catch (IOException e) {
			return null;
		}
	}

	private HashMap<String, PageFillingEvent> events = new HashMap<String, PageFillingEvent>();
	
	public HypervisorInfoService() throws IOException {
		super(ParadiseHypervisor.hypervisor.getSettings().getInfoServerAddress());
	}
	
	public void addListener(String page, PageFillingEvent event){
		events.put(page, event);
	}
	
	@Override
	public Response serve(String uri, String method, Properties header,
			Properties parms, Properties files, InputStream body) {
		log.trace("Servicing " + uri);
		Response r = new Response();
		
		if (uri.equals("/"))
			createCorePage(r);
		if (uri.equals("/styles.css"))
			createStylesFile(r);
		
		return r;
	}

	private void createCorePage(Response r) {
		htmlResponse(r);
		processPage(r, MAIN, fromResources("main.html"));
	}

	private void processPage(Response r, String id, String data) {
		PageFillingEvent event = events.get(id);
		if (event != null)
			data = event.fillPage(id, data);
		r.data = IOUtils.toInputStream(data);
	}

	private void htmlResponse(Response r) {
		r.mimeType = "text/html";
	}

	private void createStylesFile(Response r) {
		r.mimeType = "text/css";
		r.data = fromResourcesAsStream("styles.css");
	}
	
	
	
}
